<template>
  <div class="register">
    <div class="login-content">
      <div class="login-password">
        <h1 style="text-align: center;padding: 40px;"></h1>
        <el-menu :default-active="menuActiveIndex" class="el-menu" mode="horizontal" @select="selectMenu">
          <el-menu-item index="1">手机号注册</el-menu-item>
          <el-menu-item index="2">邮箱注册</el-menu-item>
        </el-menu>
        <div v-if="menuType === 'authCode'">
          <el-form :model="authCodeForm" ref="login-form" class="login-form">
            <el-input v-model="authCodeForm.mobile" placeholder="请输入手机号码" class="input-text username input-with-select"></el-input>
            <div class="input-text input-wrap-password">
              <el-input v-model="authCodeForm.authCode" placeholder="请输入验证码">
                <template #append>
                  <el-button @click="getAuthCode(authCodeAppendValue)">{{authCodeAppendValue}}</el-button>
                </template>
              </el-input>
            </div>
            <div class="forgot-password-links" style="margin-bottom: 13px;">
              <a target="_blank"></a>
            </div>
          </el-form>
        </div>
        <div v-if="menuType === 'password'">
          <el-form :model="passwordForm" ref="login-form" class="login-form">
            <el-input v-model="passwordForm.email" class="input-text username" placeholder="请输入邮箱"/>
            <div class="input-wrap-password" style="margin-bottom: 10px;">
              <el-input v-model="passwordForm.password" :type="passwordType" class="input-text" placeholder="请输入登录密码" maxlength="40"/>
              <div class="password-look-btn" @click="showPasswordChange">
                <i class="iconfont" :class="{'icon-eye-close': !showPassword, 'icon-eye-open': showPassword}"></i>
              </div>
            </div>
            <div class="input-wrap-password">
              <el-input v-model="passwordForm.confirmPassword" :type="passwordType" class="input-text" placeholder="再次输入登录密码" maxlength="40"/>
              <div class="password-look-btn" @click="showPasswordChange">
                <i class="iconfont" :class="{'icon-eye-close': !showPassword, 'icon-eye-open': showPassword}"></i>
              </div>
            </div>
            <div class="forgot-password-links" style="margin-bottom: 12px;">
              <a target="_blank"></a>
            </div>
          </el-form>
        </div>
        <div class="login-btn">
          <el-button @click="register">同意协议并注册</el-button>
        </div>
        <div class="agreement-login">
          <div class="agreement">
            <div style="text-align:center;">点击【同意协议并注册】表示您已阅读并同意本站
              <a href="/agreement/service" target="_blank" style="margin-left:0;color:#415fff;">《服务协议》</a>和
              <a href="/agreement/privacy" target="_blank" style="margin-left:0;color:#415fff;">《隐私政策》</a>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import { getDingTalkConfig, getMsgAuthCode, getWorkWeChatConfig } from "../api/login";
  import { registerMember, registerMemberByMobile} from "../api/member";
  import {reactive, ref} from "vue";
  import {error, info, success} from "../util/tipsUtils";
  import router from "../router";

  export default {
    name: "RegisterIndex",
    setup(props, context) {
      const menuActiveIndex = ref("2");
      const menuType = ref("password");
      const showPassword = ref(false);
      const passwordType = ref("password");
      const authCodeAppendLabel = "获取验证码";
      const authCodeAppendValue = ref("获取验证码");
      const loginQrCodeUrl = ref("https://img.alicdn.com/imgextra/O1CN01xstIAQ28A7zAahq9C_!!6000000007891-2-xcode.png");
      const passwordForm = reactive({
        email: "",
        password: "",
        confirmPassword: ""
      });
      const authCodeForm = reactive({
        mobile: "",
        authCode: ""
      });
      // 关闭组件回调
      const close = () => {
        context.emit("callback");
      };
      // 选择登录方式
      const oAuth2Type = ref("");
      const selectMenu = index => {
        menuActiveIndex.value = index;
        switch (menuActiveIndex.value) {
        // 验证码
        case "1":
          menuType.value = "authCode";
          break;
        // 密码
        case "2":
          menuType.value = "password";
          break;
        }
      };
      const selectOauth2 = (type) => {
        oAuth2Type.value = type
        menuType.value = "qrCode";
        const schema = window.location.protocol
        const host = window.location.host
        let redirectUri = schema + "//" + host + "/ding-talk"
        switch (type) {
        case "ding-talk":
          getDingTalkConfig((res) => {
            const url = "https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=" + res.appId + "&response_type=code&scope=snsapi_login&state=STATE"
            window.DDLogin({
              id: "ding-talk-body",
              goto: encodeURIComponent(url + "&redirect_uri="+ redirectUri),
              style: "border:none;background-color:#FFFFFF;",
              width: "300",
              height: "400"
            });
            const handleMessage = function (event) {
              const origin = event.origin;
              console.log("origin", event.origin);
              //判断是否来自ddLogin扫码事件。
              if (origin === "https://login.dingtalk.com") {
                const loginTmpCode = event.data;
                //获取到loginTmpCode后就可以在这里构造跳转链接进行跳转了
                window.location.href = url + "&redirect_uri="+ encodeURIComponent(redirectUri) + "&loginTmpCode=" + loginTmpCode
              }
            };
            if (typeof window.addEventListener != "undefined") {
              window.addEventListener("message", handleMessage, false);
            } else if (typeof window.attachEvent != "undefined") {
              window.attachEvent("onmessage", handleMessage);
            }
          })
          break;
        case "work-we-chat":
          getWorkWeChatConfig((res) => {
            window.WwLogin({
              "id": "work-we-chat-body",
              "appid": res.appId,
              "agentid": res.agentId,
              "redirect_uri": encodeURIComponent(schema + "//" + host + "/work-we-chat"),
              "state": res.state,
              "href": ""
            })
          })
          break;
        }
      }
      // 显示密码
      const showPasswordChange = () => {
        showPassword.value = !showPassword.value;
        if (showPassword.value) {
          passwordType.value = "text";
        } else {
          passwordType.value = "password";
        }
      };
      // 获取验证码
      const getAuthCode = value => {
        if (value !== authCodeAppendLabel) {
          return;
        }
        if (!authCodeForm.mobile) {
          error("请输入手机号码");
          return;
        }
        // 获取验证码
        getMsgAuthCode(authCodeForm.mobile, () => {
          let times = 60;
          const timer = setInterval(() => {
            times--;
            if (times === 0) {
              authCodeAppendValue.value = authCodeAppendLabel;
              clearInterval(timer);
            } else {
              authCodeAppendValue.value = times + "";
            }
          }, 1000);
          info("暂不发送短信，统一验证码为：123456");
        });
      };
      const register = () => {
        if (menuType.value === "password") {
          if (!passwordForm.email) {
            error("请输入邮箱")
            return;
          }
          if (!passwordForm.password) {
            error("请输入密码")
            return;
          }
          if (!passwordForm.confirmPassword) {
            error("请再次输入密码")
            return;
          }
          if (passwordForm.confirmPassword !== passwordForm.password) {
            error("两次密码不一致")
            return;
          }
          registerMember(passwordForm, () => {
            success("注册成功");
            router.push("/index");
            // passwordLogin({
            //   username: passwordForm.email,
            //   password: passwordForm.password
            // }, res => {
            //   success("登录成功");
            //   const accessToken = { expiresIn: res.expires_in, value: res.access_token };
            //   const refreshToken = res.refresh_token;
            //   const data = { accessToken: accessToken, refreshToken: refreshToken };
            //   // 保存登录信息
            //   setToken(data)
            //   getMember()
            // });
          })
        } else if (menuType.value === "authCode") {
          if (!authCodeForm.mobile) {
            error("请输入手机号码")
            return;
          }
          if (!authCodeForm.authCode) {
            error("请输入验证码")
            return;
          }
          registerMemberByMobile(authCodeForm, () => {
            success("注册成功");
            // authCodeLogin(authCodeForm, (res) => {
            //   success("登录成功");
            //   const accessToken = { expiresIn: res.expires_in, value: res.access_token };
            //   const refreshToken = res.refresh_token;
            //   const data = { accessToken: accessToken, refreshToken: refreshToken };
            //   // 保存登录信息
            //   setToken(data)
            //   getMember()
            // })
            router.push("/index");
          })
        }
      };
      return {
        // 变量
        menuActiveIndex,
        menuType,
        showPassword,
        passwordType,
        authCodeAppendValue,
        loginQrCodeUrl,
        passwordForm,
        authCodeForm,
        oAuth2Type,
        // 方法
        close,
        selectMenu,
        showPasswordChange,
        getAuthCode,
        selectOauth2,
        register
      };
    }
  };
</script>

<style lang="scss">
  .register {
    background-color: #fff;
    padding-bottom: 13px;
    min-width: 424px;
    width: 60%;
    max-width: 524px;
    margin: 70px auto 0;
    border-radius: 8px;
    .el-dialog__body {
      padding: 0;
    }
    .login-content {
      width: 100%;
      margin: 0 auto;
      .login-password {
        padding: 0 48px;
      }
      .el-menu {
        background: rgba(255,255,255, 0);
        border: none;
        li {
          width: 50%;
          height: 42px;
          line-height: 42px;
          text-align: center;
          font-size: 18px;
          font-weight: 500;
          color: #999;
        }
        li:hover, li:focus {
          background: rgba(255,255,255, 0);
          color: #999;
        }
        li.is-active {
          color: #415fff;
          border-color: #415fff;;
        }
      }
      .username {
        margin-top: 34px;
        input {
          margin-bottom: 10px;
        }
      }
      .input-text {
        input {
          height: 42px;
          outline: none;
          width: 100%;
          background: none;
          border: none;
          border-bottom: 1px solid #d8d8d8;
          font-size: 14px;
          padding-left: 0;
          color: #000;
          border-radius: 0;
        }
        .el-input-group__append {
          height: auto;
        }
      }
      .input-wrap-password {
        position: relative;
        font-size: 14px;
      }
      .password-look-btn {
        position: absolute;
        right: 10px;
        top: 10px;
        .iconfont {
          font-style: normal;
          -webkit-font-smoothing: antialiased;
          -moz-osx-font-smoothing: grayscale;
          font-size: 20px;
          display: block;
          background-size: contain;
          width: 24px;
          height: 24px;
        }
        .icon-eye-close {
          background-image: url("../assets/login/eye-close.png");
        }
        .icon-eye-open {
          background-image: url("../assets/login/eye-open.png");
        }
      }
      .login-btn {
        width: 100%;
        margin: 30px 0;
        button {
          outline: none;
          color: #fff;
          width: 100%;
          cursor: pointer;
          height: 48px;
          line-height: 48px;
          text-align: center;
          border: none;
          border-radius: 30px;
          font-size: 16px;
          background: #415fff;;
          padding: 0;
        }
      }
      .agreement-login {
        zoom: 1;
        text-align: center;
        font-size: 13px;
        margin: 12px 0;
        color: #666;
        .agreement {
          margin-bottom: 8px;
          font-size: 13px;
          line-height: 18px;
          a {
            text-decoration: none;
            display: inline-block;
            font-size: 13px;
            margin-left: 0;
            color: #415fff;;
          }
        }
      }
      .sns-login-block {
        zoom: 1;
        text-align: center;
        position: relative;
        height: 122px;
        margin: 18px 0 0;
        .sns-login {
          margin: 10px 0;
          float: none;
          .sns-login-title {
            font-size: 13px;
            line-height: 18px;
            color: #666666;
          }
          .sns-login-title:before, .sns-login-title:after {
            content: "";
            display: inline-block;
            width: 30px;
            height: 1px;
            margin: 0 12px;
            vertical-align: middle;
            background-color: #3b3b42;
          }
          .oauth2-login {
            float: none;
            display: flex;
            justify-content: space-between;
            margin-top: 12px;
            a {
              margin-left: 0;
            }
            .oauth2-login-icon {
              background-size: contain;
              background-position: 0 0;
              display: inline-block;
              background-repeat: no-repeat;
              margin: 0;
              width: 36px;
              height: 36px;
            }
          }
        }
        a:hover {
          color: #415fff;;
        }
        a{
          text-decoration: none;
          display: inline-block;
          margin-left: 10px;
          cursor: pointer;
        }
        .registerLink, .forgotLoginIdLink {
          bottom: 0;
          font-size: 14px;
          line-height: 20px;
          color: #999;
        }
        .registerLink {
          // left: -30px;
          margin: 20px auto 0;
        }
        .forgotLoginIdLink {
          right: -30px;
        }
      }
    }
    .el-input-group__prepend {
      border: none;
      width: 86px!important;
    }
    .el-input-group__prepend, .el-input-group__append {
      border-radius: 0!important;;
      width: 66px;
      background: rgba(255,255,255, 0);
      height: 42px;
      border-right: none;
      border-top: none;
      border-left: none;
      margin-bottom: 10px;
      padding: 0;
      .el-select {
        height: 42px;
        margin: 0 0 10px;
        input {
          border: none;
          margin: 0;
        }
      }
      .el-input__suffix-inner {
        height: 20px;
        border-right: 1px solid #eee;
      }
      .el-input--suffix {
        height: 42px;
        border-bottom: 1px solid #ccc;
      }
      .el-select:hover, .el-select:focus {
        color: #000;
        border-bottom: 1px solid #ccc;
      }
    }
    .el-input-group__append{
      text-align: center;
    }
  }
</style>
